package com.xidian.zhiancloud.controller.myyb;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.xidian.zhiancloud.controller.base.BaseController;
import com.xidian.zhiancloud.dto.ResultDTO;
import com.xidian.zhiancloud.enums.GeneralResponseEnums;
import com.xidian.zhiancloud.model.ExcelTest;
import com.xidian.zhiancloud.model.SysOrganizationAbandon;
import com.xidian.zhiancloud.model.SysUserAbandon;
import com.xidian.zhiancloud.service.myyb.OrganizationAbandonService;
import com.xidian.zhiancloud.service.myyb.ISysUserService;
import com.xidian.zhiancloud.util.annotation.CurrentUser;
import com.xidian.zhiancloud.util.api.ExcelUtil2;
import com.xidian.zhiancloud.util.constants.SystemConstants;
import com.xidian.zhiancloud.util.tools.PageUtil;
import com.xidian.zhiancloud.util.tools.Query;
import com.xidian.zhiancloud.util.tools.RequestUtil;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;

/**
 * 系统设置-用户管理
 *
 */
@RestController
@RequestMapping("/user")
public class User1Controller extends BaseController {

    private final static Logger logger = LoggerFactory.
            getLogger(User1Controller.class);

    @Autowired
    private ISysUserService userService;

    @Autowired
    private OrganizationAbandonService organizationService;

    /**
     * 用户列表
     * @param user
     * @param params 多个参数集合
     * @return 返回 ResultDTO 对象
     */
    @GetMapping("/user_list")
    public ResultDTO list(@CurrentUser SysUserAbandon user,
                          @RequestParam Map<String, Object> params) {
        SysUserAbandon users = null;//getSessionUser();
        //只有超级管理员，才能查看所有管理员列表
        if (!SystemConstants.SUPER_ADMIN.equals(user.getId())) {
            params.put("companyId", user.getCompanyId());
        }
        //查询列表数据
        Query query = new Query(params);
        List<SysUserAbandon> userList = userService.queryList(query);
        int total = userService.queryTotal(query);
        PageUtil pageUtil = new PageUtil(userList, total, query.getSize(), query.getPage());
        return ResultDTO.successOf(pageUtil,GeneralResponseEnums.SUCCESS);
    }

    /**
     * 删除用户
     * @param id 用户ID
     * @return 返回 ResultDTO 对象
     */
    @GetMapping("/deleteUser")
    public ResultDTO<Boolean> deleteUser(@RequestParam("id") Long id) {
        userService.deleteById(id);
        return ResultDTO.successOf(GeneralResponseEnums.SUCCESS);
    }

    /**
     * 编辑用户信息
     * @param user 用户数据
     * @return 返回 ResultDTO 对象
     */
    @PatchMapping("/patchById")
    public ResultDTO<Boolean> patchById(SysUserAbandon user) {
        userService.patchById(user);
        return ResultDTO.successOf(GeneralResponseEnums.SUCCESS);
    }

    /**
     * 添加
     * @param user 用户数据
     * @return 返回 ResultDTO 对象
     */
    @PostMapping("/add")
    public ResultDTO<Boolean> add(SysUserAbandon user) {
        userService.add(user);
        return ResultDTO.successOf(GeneralResponseEnums.SUCCESS);
    }

    /**
     * 批量删除
     * @param ids 用户IDs
     * @return 返回 ResultDTO 对象
     */
    @DeleteMapping("/deleteByIds")
    public ResultDTO<Boolean> deleteByIds(Long[] ids) {
        userService.deleteByIds(ids);
        return ResultDTO.successOf(GeneralResponseEnums.SUCCESS);
    }

    /**
     * 将用户表导出到excel文件中去
     * @param * 用户信息列表
     * @param * 输出表
     * @throws IOException
     */
    @RequestMapping("/exportUserEx")
    public void exportUser( HttpServletRequest request, HttpServletResponse response) throws IOException {

        String orgi ="user";

        String id = RequestUtil.getStringParameter(request, "id","") ;//ID
        String jobNum = RequestUtil.getStringParameter(request,
                "jobNum","");//工号
        String phoneNum = RequestUtil.getStringParameter(request,
                "phoneNum","");//手机号码
        String username= RequestUtil.getStringParameter(request, "username","");//真实姓名
        String department= RequestUtil.getStringParameter(request, "department","");//部门
        String position= RequestUtil.getStringParameter(request, "position","");//职位
        String post = RequestUtil.getStringParameter(request, "post","") ;//岗位
        String major = RequestUtil.getStringParameter(request,
                "major","");//专业
        String idNum = RequestUtil.getStringParameter(request,
                "idNum","");//身份证号
        String sex= RequestUtil.getStringParameter(request, "sex","");//性别
        String age= RequestUtil.getStringParameter(request, "age","");//年龄
        String mail= RequestUtil.getStringParameter(request, "mail","");//电子邮箱
        String entryTime=RequestUtil.getStringParameter(request, "entryTime","");//入职时间

        Map<String, Object> mapResult =new HashMap<String, Object>();

        mapResult.put("id", id);
        mapResult.put("jobNum", jobNum);
        mapResult.put("phoneNum", phoneNum);

        mapResult.put("username", username);
        mapResult.put("department", department);
        mapResult.put("position", position);
        mapResult.put("post", post);
        mapResult.put("major", major);
        mapResult.put("idNum", idNum);

        mapResult.put("sex", sex);
        mapResult.put("age", age);
        mapResult.put("mail", mail);
        mapResult.put("entryTime", entryTime);

        List<SysUserAbandon> userList = null;

        if (
                StringUtils.isNotEmpty(id) || StringUtils.isNotEmpty(jobNum) ||
                StringUtils.isNotEmpty(phoneNum) || StringUtils.isNotEmpty(username)
                || StringUtils.isNotEmpty(department) || StringUtils.isNotEmpty(position)
                || StringUtils.isNotEmpty(post) || StringUtils.isNotEmpty(major) ||
                StringUtils.isNotEmpty(idNum) || StringUtils.isNotEmpty(sex) ||
                StringUtils.isNotEmpty(age) || StringUtils.isNotEmpty(mail) ||
                StringUtils.isNotEmpty(entryTime)
        ) {
            userList = userService.selectUserList(mapResult);
        }

        //else if(
//                StringUtils.isEmpty(id) || StringUtils.isEmpty(jobNum) ||
//                StringUtils.isEmpty(phoneNum) || StringUtils.isEmpty(username)
//                || StringUtils.isEmpty(department) || StringUtils.isEmpty(position) ||
//                StringUtils.isEmpty(post) || StringUtils.isEmpty(major) ||
//                StringUtils.isEmpty(idNum) || StringUtils.isEmpty(sex) ||
//                StringUtils.isEmpty(age) || StringUtils.isEmpty(mail) ||
//                StringUtils.isEmpty(entryTime)
//                ) {
//        organizationList = userService.findByOrgiOrderByCreatetimeDesc(orgi);
//        }

        response.reset(); // 必要地清除response中的缓存信息

        response.setCharacterEncoding("utf-8");
        response.setContentType("application/vnd.ms-excel");
        String  fileName="用户信息表.xls";

        if (request.getHeader("User-Agent").toLowerCase().indexOf("firefox") > 0)  {
            fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");
            // firefox浏览器
        } else if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {
            fileName = URLEncoder.encode(fileName, "UTF-8");// IE浏览器
        } else if (request.getHeader("User-Agent").toUpperCase().indexOf("CHROME") > 0) {
            fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");
            // 谷歌
        }

        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);

        //07版本以前的Excel文件,即后缀名为.xls,
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet("user");
        HSSFRow row;
        HSSFCell cell;
        String createtime="";
        String updatetime="";
        row = sheet.createRow(0);
        String[] titles = {"序号","工号","手机号码","真实姓名","部门","职位","是否为部门负责人","岗位","专业","身份证号","性别","年龄","电子邮箱","入职时间"};
        for (int i = 0; i < titles.length; i++) { // 创建一个单元格，设置单元格的值
            cell = row.createCell(i);
            cell.setCellValue(titles[i]);
        }
        // 从第1行开始写数据
        for (int i = 0; i < userList.size(); i++) {
            // 创建表格的第i+1行
            row = sheet.createRow(i + 1);
            // 写该行的各列数据
            SysUserAbandon user = userList.get(i);
            int j = 0;

            SysOrganizationAbandon organization = new SysOrganizationAbandon();
            organization=organizationService.getById(user.getOrganizationId());
            Long positionId = organization.getPositionId();//部门负责人ID
            int z;
            if (positionId.equals(user.getId())){
                z=1;
            }else {
                z=0;
            }
            cell = row.createCell(j++);
            cell.setCellValue(i + 1); // 序号
            cell = row.createCell(j++);
            cell.setCellValue(user.getJobNum());//工号
            cell = row.createCell(j++);
            cell.setCellValue(user.getPhoneNum());//手机号码
            cell = row.createCell(j++);
            cell.setCellValue(user.getUsername());//真实姓名
            cell = row.createCell(j++);
            //修改--6
            //cell.setCellValue(user.getDepartment());//部门
            cell = row.createCell(j++);
            cell.setCellValue(user.getPositionId());//职位
            cell = row.createCell(j++);
            cell.setCellValue(z == 0 ? "不是" : "是");//是否为部门负责人
            cell = row.createCell(j++);
            cell.setCellValue(user.getPostId());//岗位
            cell = row.createCell(j++);
            cell.setCellValue(user.getMajor());//专业
            cell = row.createCell(j++);
            cell.setCellValue(user.getIdNum());//身份证号
            cell = row.createCell(j++);
            cell.setCellValue(user.getSex());//性别
            cell = row.createCell(j++);
            cell.setCellValue(user.getAge());//年龄
            cell = row.createCell(j++);
            cell.setCellValue(user.getMail());//电子邮箱
            cell = row.createCell(j++);
            cell.setCellValue(user.getEntryTime());//入职时间

        }

        // 将excel的数据写入文件
        javax.servlet.ServletOutputStream os = response.getOutputStream();
        wb.write(os);
        os.close();

    }

    /**
     * 将用户表导入到数据库
     * @param srcFile
     * @param redirectAttributes
     * @return
     * @throws Exception
     */
//    @RequestMapping("/fileUploadUser")
//    public String fileUploadUser(@RequestParam("file") MultipartFile srcFile, RedirectAttributes redirectAttributes) throws Exception{
//        //前端没有选择文件，srcFile为空
//        if(srcFile.isEmpty()) {
//            redirectAttributes.addFlashAttribute("message", "请选择一个文件");
//            return "redirect:update_status";
//        }
//        String line =null;
//        JSONArray dataJson =new JSONArray();
//
//        //选择了文件，开始上传操作
//        try {
//            //构建上传目标路径，找到了项目的target的classes目录
//            File destFile = new File(ResourceUtils.getURL("classpath:").getPath());
//            if(!destFile.exists()) {
//                destFile = new File("");
//            }
//            //输出目标文件的绝对路径
//            // System.out.println("file path:"+destFile.getAbsolutePath());
//            //拼接子路径
//            SimpleDateFormat sf_ = new SimpleDateFormat("yyyyMMddHHmmss");
//            String times = sf_.format(new Date());
//            File upload = new File(destFile.getAbsolutePath(), "picture/"+times);
//            //若目标文件夹不存在，则创建
//            if(!upload.exists()) {
//                upload.mkdirs();
//            }
//            // System.out.println("完整的上传路径："+upload.getAbsolutePath()+"/"+srcFile);
//            //根据srcFile大小，准备一个字节数组
//            byte[] bytes = srcFile.getBytes();
//            //拼接上传路径
//            //Path path = Paths.get(UPLOAD_FOLDER + srcFile.getOriginalFilename());
//            //通过项目路径，拼接上传路径
//            Path path = Paths.get(upload.getAbsolutePath()+"/"+srcFile.getOriginalFilename());
//            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
//            // 获得文件原始名称
//            String fileName = srcFile.getOriginalFilename();
//            // 获得文件后缀名称
//            String suffixName = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
//            // 生成最新的uuid文件名称
//            String newFileName = uuid + "."+ suffixName;
//            //** 开始将源文件写入目标地址
//            Files.write(path, bytes);
//            String oldName = "";
//            String projectUrl = upload.getAbsolutePath()+"/"+srcFile.getOriginalFilename();
//            String version = ExcelUtil.isExcel2003(fileName)?"2003":"2007";
//
//            if (fileName.endsWith(".xls")){
//                oldName = fileName.substring(0,fileName.length()-4);
//            }else if (fileName.endsWith(".xlsx")){
//                oldName = fileName.substring(0,fileName.length()-5);
//            }
//            File f = new File(projectUrl);
//            InputStream in = new FileInputStream(f);
//            ExcelUtil excelUtil = new ExcelUtil(in, version);
//            List<List<String>> read = excelUtil.read(0);
//            int sheet = excelUtil.getRowCount(0);//列数
//            int totalRows = excelUtil.getColumnCount(0,0);//行数
//            JSONArray json =new JSONArray();
//            File filez = new File(upload.getAbsolutePath()+"/"+oldName+".txt");
//            if(!filez.exists()){
//                filez.createNewFile();
//            }
//            // 获取该文件的缓冲输出流
//            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filez), "UTF-8"));
//            String demoJson  ="";
//            List<String> rowList = new ArrayList<>();
//
//            for (int j = 1;j<read.size();j++) {
//                rowList = read.get(j);
//                for (int z=0;z<totalRows;z++){
//                    for (String s : rowList){
//                        SysUserAbandon user = new SysUserAbandon();
//                        user.setId(Long.valueOf(rowList.get(0).toString()));//序号
//                        if (rowList.get(1).toString().equals("") ||
//                                rowList.get(1).toString() == null) {//工号
//                            user.setJobNum("");
//                        } else {
//                            user.setJobNum(rowList.get(1).toString());
//                        }
//                        if (rowList.get(2).toString().equals("") ||
//                                rowList.get(2).toString() == null) {//手机号码
//                            user.setPhoneNum("");
//                        } else {
//                            user.setPhoneNum(rowList.get(2).toString());
//                        }
//                        if (rowList.get(3).toString().equals("") ||
//                                rowList.get(3).toString() == null) {//真实姓名
//                            user.setUsername("");
//                        } else {
//                            user.setUsername(rowList.get(3).toString());
//                        }
//                        //修改--7
//                       /* if (rowList.get(4).toString().equals("") ||
//                                rowList.get(4).toString() == null) {//部门
//                            user.setDepartment("");
//                        } else {
//                            user.setDepartment(rowList.get(4).toString());
//                        }*/
//                        if (rowList.get(5).toString().equals("") ||
//                                rowList.get(5).toString() == null) {//职位
//                            user.setPositionId(Long.valueOf(""));
//                        } else {
//                            user.setPositionId(Long.valueOf(rowList.get(5).toString()));
//                        }
////                        if (rowList.get(6).toString().equals("") ||
////                                rowList.get(6).toString() == null) {
////
////                        } else {
////                            user.setLeader(rowList.get(6).toString());
////                        }
//                        if (rowList.get(7).toString().equals("") ||
//                                rowList.get(7).toString() == null) {//岗位
//                            user.setPostId(Long.valueOf("0"));
//                        } else {
//                            user.setPostId(Long.valueOf(rowList.get(7).toString()));
//                        }
//                        if (rowList.get(8).toString().equals("") ||
//                                rowList.get(8).toString() == null) {//专业
//                            user.setMajor("");
//                        } else {
//                            user.setMajor(rowList.get(8).toString());
//                        }
//                        if (rowList.get(9).toString().equals("") ||
//                                rowList.get(9).toString() == null) {//身份证号
//                            user.setIdNum("");
//                        } else {
//                            user.setIdNum(rowList.get(9).toString());
//                        }
//                        if (rowList.get(10).toString().equals("") ||
//                                rowList.get(10).toString() == null) {//性别
//                            user.setSex(null);
//                        } else {
//                            user.setSex(Byte.valueOf(rowList.get(10).toString()));
//                        }
//                        if (rowList.get(11).toString().equals("") ||
//                                rowList.get(11).toString() == null) {//年龄
//                            user.setAge(null);
//                        } else {
//                            user.setAge(Integer.valueOf(rowList.get(11).toString()));
//                        }
//                        if (rowList.get(12).toString().equals("") ||
//                                rowList.get(12).toString() == null) {//电子邮箱
//                            user.setMail(null);
//                        } else {
//                            user.setMail(rowList.get(10).toString());
//                        }
//                        if (rowList.get(13).toString().equals("") ||
//                                rowList.get(13).toString() == null) {//入职时间
//                            user.setEntryTime(null);
//                        } else {
//                            user.setEntryTime( new Date(rowList.get(13).toString()));
//                        }
//                        user.setRoleId(1);//角色ID
//                        user.setCompanyId(null);//公司ID
//                        user.setPasswords("");//密码
//                        user.setStatus(0);//删除标志
//                        user.setCreateTime(new Date());//创建时间
//                        user.setUpdateTime(new Date());//更新时间
//                        userService.add(user);
//                        break;
//                    }
//                    break;
//                }
//            }
//
//            bufferedWriter.close();
//            redirectAttributes.addFlashAttribute("message", "文件上传成功"+newFileName);
//            String dataBuckets = upload.getAbsolutePath()+"/"+oldName+".txt";
//            FileInputStream fileInputStream = new FileInputStream(dataBuckets);
//            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream));
//            line = bufferedReader.readLine();
//        } catch(IOException e) {
//            e.printStackTrace();
//        }
//        return "redirect:user/user_list";
//    }


    @GetMapping("/export")
    public void export(HttpServletResponse response, ExcelTest test) throws IOException
    {
    	
        List<ExcelTest> test2 = new ArrayList<>();
    	for (int i = 0; i < 5; i++) {
    		ExcelTest excel = new ExcelTest();
    		excel.setJob("job"+i);
    		excel.setName("老王"+i);
    		test2.add(excel);
		}
        ExcelUtil2<ExcelTest> util = new ExcelUtil2<ExcelTest>(ExcelTest.class);
        util.exportExcel(response, test2, "测试");
    }

}
